<template>
	<!--  #ifndef  APP-PLUS -->
	<custom-nav></custom-nav>
	<!--  #endif -->
	<view class="page-history" :style="pagePaddingTop">
		<template v-if="pageLoading">
			<view class="container-search-clear">
				<view class="box-search" :class="{'show-print' : showPrint}">
					<comp-search v-model="txtSearch" @confirm="onConfirmSearch"></comp-search>
				</view>
				<template v-if="showPrint">
					<button class="exit-print" type="default" @tap="onExitPrint">退出打印</button>
					<button class="confirm-print" type="default" @tap="onConfirmPrint">确认打印</button>
				</template>
				<template v-else>
					<view class="container-clear" @tap="onShowClear">
						<image class="icon-clear" src="/static/icon_clear.png"></image>
						<text>清空</text>
					</view>
					<view class="container-clear" @tap="onShowPrint">
						<image class="icon-clear" src="/static/icon_print@2x.png"></image>
						<text>打印</text>
					</view>
				</template>
			</view>
			<view class="container-filter">
				<view class="wrap-filter" @tap="handleShowFilter">
					{{filterList&&filterList[filterIndex]?(filterList[filterIndex].mid_table_remark_001):'全部'}}
					<image :class="['icon-arrow-down',showFilterDialog?'up':'']" src="/static/icon_arrow_down2.png">
					</image>
				</view>
				<view ref="refCompPicker" id="refCompPicker">
					<CustomPicker componentId="historyFilter" :optionList="filterList"
						v-model:visible='showFilterDialog' v-model:selectedIdx='filterIndex' :domInfo="pickerDomInfo">
					</CustomPicker>
				</view>

			</view>
			<view class="container-history">
				<view class="container-history-body">
					<scroll-view class="scview-history" scroll-y @scrolltolower="onScrollBottom">
						<view class="wrap-history" v-if="dateHistory&&dateHistory.length">
							<view v-for="(item,idx) in dateHistory" :key="idx" class="item-history">
								<view class="cont-date">
									<view class="dot"></view>{{item.date}}
								</view>
								<view v-for="(itemMain,idxMain) in item.list" :key="idxMain" class="check-container">
									<view v-if="showPrint">
										<image v-if="itemMain.checked" class="prev-icon checked"
											src="/static/icon_selected@2x.png" @tap="onCheck(itemMain)"></image>
										<view v-else class="prev-icon uncheck" @tap="onCheck(itemMain)"></view>
									</view>
									<view class="item-title-arrow" @tap="handleToChat(itemMain)">
										<view class="cont-title">{{itemMain.show_middle_table_remark_001}}</view>
										<image class="img-arrow" src="/static/icon_arrow_down2.png"></image>
									</view>
								</view>

							</view>
						</view>
						<view v-else class="box-empty">
							<image class="icon-none" src="/static/icon_none.png"></image>
						</view>
					</scroll-view>
				</view>
			</view>
		</template>
		<view class="tabbar-border"></view>
	</view>
	<custom-modal ref='refClearModal' v-model:visible='showClear' content='您确定要清空历史记录吗？' :showCancelButton='true'
		@clickCallback="OnClearHistory"></custom-modal>
	<custom-modal ref='refClearModal' v-model:visible='showLogin' content='您未登录,请先登录？' :showCancelButton='false'
		@clickCallback="toLogin"></custom-modal>
</template>

<script setup>
	import {
		ref,
		watch,
		nextTick
	} from "vue";
	import {
		onLoad,
		onShow,
		onUnload,
		onReachBottom
	} from "@dcloudio/uni-app"
	import {
		showDecodeBase64,
		// showBRContent,
		encodeBase64
	} from "@/utils/tool.js"
	import {
		getNavHeightTop
	} from "@/stores/navStore.js"
	import CompSearch from "@/components/search/index.vue"
	import CustomPicker from "/components/custom-picker/index.vue"
	import CustomModal from "@/components/custom-modal/index.vue"
	import CustomNav from "@/components/custom-nav/index.vue"
	import {
		useUser
	} from "@/hooks/useUser.js"
	import usePicker from "@/hooks/usePicker.js"
	import {
		middleAPI
	} from "@/http/apis/middleAPI.js"
	import {
		showToast
	} from "../../utils/frameApi";
	const userStore = useUser();
	let navHeightInfo = getNavHeightTop();
	const pagePaddingTop = ref({
		"paddingTop": navHeightInfo.navTotalHeight + 'px'
	})
	// #ifdef APP-PLUS
	pagePaddingTop.value = {
		"paddingTop": navHeightInfo.statusBarHeight + 'px'
	}
	// #endif
	let userInfo = ref(null)

	let txtSearch = ref("");
	let filterList = ref([])

	let filterIndex = ref(0);
	let showFilterDialog = ref(false);
	const handleShowFilter = () => {
		if (!goLogin()) {
			return;
		}
		let val = showFilterDialog.value
		showFilterDialog.value = !val;
	}



	let dateHistory = ref([])
	// for (var i = 0; i < 5; i++) {
	// 	dateHistory.value.push(dateHistory.value[0])
	// }


	// 清理
	const showClear = ref(false);
	const onShowClear = () => {
		if (!dateHistory.value || dateHistory.value.length <= 0) {
			showToast({
				title: "暂未历史记录"
			})
			return;
		}
		if (!goLogin()) {
			return;
		}
		showClear.value = true;
	}
	/*print code start*/
	const showPrint = ref(false);
	// 显示打印弹窗
	const onShowPrint = () => {
		showPrint.value = true;
	}
	// 退出打印
	const onExitPrint = () => {
		showPrint.value = false;
	}
	// 确认打印
	const onConfirmPrint = () => {
		const checkedList = dateHistory.value.reduce((c, dateItem) => {
			dateItem.list.forEach(item => {
				if(item.checked){
					c.push(item);
				}
			});
			return c;
		}, []);
		if(!checkedList.length) return showToast({title:"请勾选打印内容"});
		uni.navigateTo({
			url: `/pages/print/index?printList=${JSON.stringify(checkedList)}`
		});
		console.log('checkedList', checkedList);
	}
	
	const onCheck = (itemMain) => {
		itemMain.checked = !itemMain.checked
	}
	/*print code end*/

	// picker
	let pickerDomInfo = ref(null)


	// 加载分类
	let industryList = ref([])
	const getIndustryList = () => {
		let postData = {
			invoke_method: "public_load_middle_table_list",
			pre_db_para_middle_table_name: "public_middle_table_lite_mod_ai_chatgpt",
			type_middle_app: 12001,
			type_inner_app: 1001,
			is_online: 0,
			pre_db_para_begin_idx: 0,
			pre_db_para_length_4_list: 5,
			pre_cmd_para_show_trade_info: true,
			pre_db_para_order_by_para: "id_public_middle_table desc",
		}
		return middleAPI(postData, false)
	}
	//加载历史列表
	let cacheList = [];
	let page = ref(1);
	const pageSize = 10;
	let notMore = ref(false)
	const getList = async () => {
		let queryData = {
			invoke_method: 'public_load_middle_table_list',
			pre_db_para_middle_table_name: 'public_middle_table_lite_mod_ai_chatgpt',
			type_middle_app: 10001,
			type_inner_app: 1001,
			is_online: 0,
			pre_db_para_begin_idx: (page.value - 1) * pageSize,
			pre_db_para_length_4_list: pageSize,
			pre_db_para_order_by_para: 'id_public_middle_table DESC',
			pre_cmd_para_show_main_info: true,
			// id_public_user_info: userInfo.value.id_public_user_info,
			pre_db_para_group_by_para: "mid_table_remark_013",
		}
		if (filterIndex.value != 0) {
			let filterItem = filterList.value[filterIndex.value];
			queryData.mid_table_remark_008 = filterItem.id_public_middle_table;
		}
		if (txtSearch.value) {
			queryData.pre_db_para_search_condition = encodeBase64(txtSearch.value)
			queryData.pre_db_para_search_condition_key = "mid_table_remark_001,mid_table_remark_002"
			// queryData.mid_table_remark_001_like = encodeBase64(txtSearch.value)
		}
		let response = await middleAPI(queryData).catch((err) => {
			console.log(err, ">>>>>")
			let nextPage = page.value - 1;

			page.value = nextPage || 1;
		})
		if (response) {

			let result = response.page_content || [];
			console.log(result, ">>>>>>>>>>>>>")
			if (result.length < pageSize) {
				notMore.value = true;
			}
			for (let i = 0; i < result.length; i++) {
				let item = result[i]
				try {
					item.show_middle_table_remark_001 = item.mid_table_remark_001;
					if (item.show_middle_table_remark_001) {
						item.show_middle_table_remark_001 = showDecodeBase64(item.show_middle_table_remark_001)												
					}
				} catch (e) {
					//TODO handle the exception
				}
			}
			cacheList = cacheList.concat(result)
			let tmpDateArr = [];
			let tmpHistory = []
			for (let i = 0; i < cacheList.length; i++) {
				let item = cacheList[i]
				let idxDate = tmpDateArr.indexOf(item.mid_table_remark_007)
				if (idxDate == -1) {
					tmpDateArr.push(item.mid_table_remark_007)
					tmpHistory.push({
						date: item.mid_table_remark_007,
						list: []
					})
					idxDate = tmpHistory.length - 1;
				}
				tmpHistory[idxDate].list.push(item)
			}
			dateHistory.value = tmpHistory
		}


	}
	let pageLoading = ref(false)

	onShow(() => {
		userStore.getUserInfo().then(async res => {
			userInfo.value = res?.public_user_info || {};
			pageLoading.value = true
			let industryResult = await getIndustryList().catch((err) => {
				console.log(err, '>>>industryResult...error')
			})
			if (industryResult) {
				let tmpList = industryResult?.page_content || []
				// tmpList.shift(0)
				tmpList.unshift({
					id_public_middle_table: 0,
					mid_table_remark_001: '全部'
				})
				industryList.value = tmpList
				filterList.value = tmpList;
				cacheList = [];
				dateHistory.value = []
				notMore.value = false;
				page.value = 1;
				getList();
			}
			nextTick(() => {
				usePicker('refCompPicker').then((res) => {
					pickerDomInfo.value = res;
					// console.log(res, ">>>>>>>>>>>>>>>>>>>")
				})
			})
		}, err => {

		})
	})
	// onReachBottom(() => {
	// 	if (notMore.value) {
	// 		return;
	// 	}
	// 	page.value += 1;
	// 	getList()
	// })
	watch(() => filterIndex.value, (val) => {
		cacheList = [];
		dateHistory.value = []
		notMore.value = false;
		page.value = 1;
		getList();
	})
	let showLogin = ref(false)
	const goLogin = () => {
		if (!userInfo.value || !userInfo.value.id_public_user_info || userInfo.value.id_public_user_info == 92) {
			// showToast({title:'您未登录，请先登录'});
			// uni.reLaunch({
			// 	url:"/pages/login/index"
			// })
			showLogin.value = true;
			return false;
		}
		return true
	}
	const toLogin = () => {
		showLogin.value = false;
		uni.reLaunch({
			url: "/pages/login/index"
		})
	}
	const onConfirmSearch = () => {
		if (!goLogin()) {
			return;
		}
		cacheList = [];
		dateHistory.value = []
		notMore.value = false;
		page.value = 1;
		getList();
	}
	const onScrollBottom = () => {
		if (notMore.value) {
			return;
		}
		page.value += 1;
		getList()
	}
	const handleToChat = (item) => {
		if (!item || !item.mid_table_remark_001 || !item.mid_table_remark_013) {
			return;
		}
		if (!goLogin()) {
			return;
		}
		uni.navigateTo({
			url: `/pages/chat/index?id=${item.mid_table_remark_008}&sessionid=${item.mid_table_remark_013}`
		})
	}
	let requesting = false;
	const OnClearHistory = (confirm) => {
		if (!dateHistory.value || dateHistory.value.length <= 0) {
			return;
		}
		if (confirm) {
			if (requesting) {
				return;
			}
			requesting = true;
			let queryData = {
				invoke_method: 'public_insert_or_update_middle_table',
				pre_db_para_middle_table_name: 'public_middle_table_lite_mod_ai_chatgpt',
				type_middle_app: 10001,
				type_inner_app: 1001,
				is_online: 111,
				pre_db_para_id_public_middle_table: -1,
				id_public_user_info: userInfo.value.id_public_user_info,
				pre_db_para_type_middle_app: 10001,
				pre_db_para_type_inner_app: 1001,
			}
			middleAPI(queryData).then(() => {
				requesting = false;
				cacheList = [];
				dateHistory.value = []
				notMore.value = false;
				page.value = 1;
				getList();
			}, err => {
				requesting = false;
			})
		}


	}
</script>

<style lang="less" scoped>
	.page-history {
		position: relative;
		width: 100%;
		height: 100vh;
		display: flex;
		display: -webkit-flex;
		flex-direction: column;
		background-color: #182836;
		box-sizing: border-box;

		.container-search-clear {
			position: relative;
			width: 100%;
			padding: 18rpx 32rpx;
			box-sizing: border-box;
			display: flex;
			display: -webkit-flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;

			.box-search {
				position: relative;
				width: 462rpx;
				height: 80rpx;
				&.show-print {
					width: 342rpx;
				}
			}
			uni-button {
				margin-left: 0;
				margin-right: 0;
				padding-left: 26rpx;
				padding-right: 26rpx;
				width: 148rpx;
				height: 64rpx;
				border-radius: 32rpx;
				font-size: 24rpx;
				font-weight: 600;
			}
			.exit-print {
				background: #213343;
				color: #FFFFFF;
			}
			.confirm-print {
				background: #00FFF6;
				color: #182836;
			}

			.container-clear {
				position: relative;
				width: 80rpx;
				height: 80rpx;
				background: #213343;
				border-radius: 16rpx;
				display: flex;
				display: -webkit-flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 18rpx;
				// font-family: PingFang SC;
				line-height: 18rpx;
				font-weight: 600;
				color: #FFFFFF;

				.icon-clear {
					position: relative;
					width: 34rpx;
					height: 34rpx;
					margin-bottom: 6rpx;
					vertical-align: top;
				}
			}
		}

		.container-filter {
			position: relative;
			width: 100%;
			// padding-left: 32rpx;
			// padding-right: 32rpx;
			padding-bottom: 8rpx;
			box-sizing: border-box;

			.wrap-filter {
				position: relative;
				width: 686rpx;
				height: 72rpx;
				border-bottom: 1px solid rgba(72, 194, 130, 0.1);
				font-size: 26rpx;
				line-height: 26rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #FFFFFF;
				box-sizing: border-box;
				display: flex;
				display: -webkit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				margin: 0 auto;

				.icon-arrow-down {
					position: relative;
					width: 24rpx;
					height: 24rpx;

					&.up {
						transform: rotate(180deg);
						-webkt-transform: rotate(180deg);
					}
				}
			}

		}

		.container-history {
			position: relative;
			width: 100%;
			flex: 1;
			box-sizing: border-box;

			.container-history-body {
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
				left: 0;

				overflow: hidden;
			}

			.scview-history {
				position: relative;
				width: 100%;
				height: 100%;

				.wrap-history {
					position: relative;
					width: 100%;
					padding-bottom: 64rpx;
					box-sizing: border-box;

					.item-history {
						position: relative;
						margin-top: 60rpx;

						.cont-date {
							position: relative;
							width: 100%;
							padding-left: 32rpx;
							padding-right: 32rpx;
							box-sizing: border-box;
							display: flex;
							display: -webkit-flex;
							flex-direction: row;
							align-items: center;
							font-size: 26rpx;
							// font-family: PingFang SC;
							font-weight: 600;
							color: #FEFEFE;
							line-height: 26rpx;

							.dot {
								position: relative;
								width: 12rpx;
								height: 12rpx;
								background: #48C282;
								border-radius: 50%;
								margin-right: 20rpx;
							}
						}

						.check-container {
							margin: 24rpx auto 0;
							padding: 36rpx;
							display: flex;
							display: -webkit-flex;
							flex-direction: row;
							align-items: center;

							.prev-icon {
								flex-shrink: 0;
								width: 36rpx;
								height: 36rpx;
								margin-right: 24rpx;
							}

							.uncheck {
								border: 1rpx solid #FFFFFF;
								border-radius: 8rpx;
								box-sizing: border-box;
							}
						}

						.item-title-arrow {
							position: relative;
							width: 686rpx;
							background: #213343;
							border-radius: 28rpx;
							padding: 40rpx 32rpx;
							box-sizing: border-box;
							display: flex;
							display: -webkit-flex;
							flex-direction: row;
							align-items: center;
							justify-content: space-between;

							.cont-title {
								position: relative;
								width: 0;
								flex: 1;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								font-size: 28rpx;
								// font-family: PingFang SC;
								font-weight: 600;
								color: #FFFFFF;
								line-height: 28rpx;
							}

							.img-arrow {
								position: relative;
								width: 30rpx;
								height: 30rpx;
								transform: rotate(-90deg);
								-webkit-transform: rotate(-90deg);
								margin-left: 10rpx;
								flex-shrink: 0;
							}
						}
					}
				}

				.box-empty {
					position: absolute;

					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					-webkit-transform: translate(-50%, -50%);

					.icon-none {
						position: relative;
						width: 326rpx;
						height: 326rpx;
						margin: 64rpx auto;
						vertical-align: top;

					}
				}
			}
		}

		.tabbar-border {
			position: fixed;
			width: 100%;
			height: 2px;
			// background-color: #48C282;

			background: #00FFF6;
			bottom: 0;
			z-index: 3;
		}
	}
</style>